<?php

namespace App\Http\Controllers\Api\Customer;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Facades\Product\UserService;
use Auth;
use App\Facades\Utils\ValidateParameter;
use App\Exceptions\ValidateParameterException;

class UserController extends Controller
{
    /**
     * 获取全部用户
     * @return [type] [description]
     */
    public function getAll()
    {
        return formatJsonResponse(UserService::getAllByConditions());
    }

    /**
     * 登陆
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function login(Request $request)
    {
        $data = $request->all();

        if (!Auth::attempt(['uname' => $data['uname'], 'password' => $data['password']])) {
            throw new ValidateParameterException('Your username or password error');
        }

        return formatJsonResponse();
    }

    public function logout(Request $request){
        Auth::logout();
        return formatJsonResponse();
    }

    /**
     * 添加用户
     * @param  Request $request [description]
     * @return [type]           [description]
     */
   public function create(Request $request){

        $rules = [
            'name' => 'required',
            'uname' => 'required|unique:users,uname',
            'password' => 'required',
            'role_id' => 'required|exists:roles,id'
        ];

        ValidateParameter::validate($request,$rules);

        UserService::createUser($request);

        return formatJsonResponse();
   }

   /**
    * 根据用户id删除用户
    * @param  Request $request [description]
    * @return [type]           [description]
    */
   public function delete(Request $request){

        $rules = [
            'id' => 'required|exists:users,id'
        ];

        ValidateParameter::validate($request,$rules);

        UserService::deleteUser($request);

        return formatJsonResponse();
   }

   /**
    * 更改自己用户信息
    * @param  Request $request [description]
    * @return [type]           [description]
    */
   public function updateOneself(Request $request){

        $rules = [
            'newPassword' => 'required',
            'confirmPassword' => 'required|same:newPassword'
        ];

        ValidateParameter::validate($request,$rules);

        UserService::updateOneself($request);

        return formatJsonResponse();
   }

   /**
    * 更改用户所有信息
    * @param  Request $request [description]
    * @return [type]           [description]
    */
   public function updateUser(Request $request){
         $rules = [
            'id' => 'required|exists:users,id',
            'uname' => 'required|unique:users,uname,'.$request->id,
            'name' => 'required'
        ];

        ValidateParameter::validate($request,$rules);

        UserService::updateUser($request);

        return formatJsonResponse();
   }
}
